<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 添加角色 -->
    <el-row>
      <el-col>
        <el-button type="primary" @click="addRole">添加角色</el-button>
      </el-col>
    </el-row>
    <!-- 卡片列表 -->
    <el-table :data="roleList" stripe style="width: 100%" border>
      <!-- 扩展列 -->
      <el-table-column type="expand">
        <template slot-scope="scoped">
          <div class="expand">
            <el-row
              v-for="(item1, i1) of scoped.row.children"
              :key="item1.id"
              :class="i1 == 0 ? 'bd-top' : ''"
              class="bd-bottom center"
            >
              <el-col :span="5">
                <!-- 渲染第一列 -->
                <el-tag closable @close="closeTag(scoped.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) of item1.children"
                  class="center"
                  :key="item2.id"
                  :class="i2 == 0 || i2 == item2.length ? '' : 'bd-top'"
                >
                  <!-- 渲染第二列 -->
                  <el-col :span="4">
                    <el-tag
                      closable
                      type="success"
                      @close="closeTag(scoped.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染第三列 -->
                  <el-col :span="20">
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 of item2.children"
                      :key="item3.id"
                      @close="closeTag(scoped.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </div>
        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column type="index" label="#"> </el-table-column>
      <el-table-column prop="roleName" label="角色名称"> </el-table-column>
      <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
      <el-table-column label="操作">
        <!-- 操作按钮 -->
        <template slot-scope="scoped">
          <el-tooltip content="编辑角色" placement="top">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="edit(scoped.row.id)"
              >编辑</el-button
            >
          </el-tooltip>
          <el-tooltip content="删除角色" placement="top">
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="del(scoped.row.id)"
              >删除</el-button
            >
          </el-tooltip>
          <el-tooltip content="分配角色" placement="top">
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="setRight(scoped.row)"
              >分配权限</el-button
            >
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加角色的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="dialogRoleVisible"
      show-close
      @close="closeRoleDialog"
    >
      <el-form
        :model="role"
        :rules="roleRules"
        ref="roleForm"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="role.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色说明" prop="roleDesc">
          <el-input v-model="role.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改角色的对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      show-close
      @close="closeEditDialog"
    >
      <el-form
        :model="editRole"
        :rules="roleRules"
        ref="editRuleForm"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="rightsTreeDialogVisible"
      show-close
    >
      <!-- 权限树形控件 -->
      <el-tree
        :data="rightsTree"
        :props="defaultProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="choosedId"
        ref="rightsTree"
      >
      </el-tree>
         <div slot="footer" class="dialog-footer">
        <el-button @click="rightsTreeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="rightsSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created() {
    this.getRoleList();
  },
  data() {
    return {
      roleList: [],
      // 添加角色提交的表单
      role: {
        roleName: "",
        roleDesc: "",
      },
      // 添加角色的规则
      roleRules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        roleDesc: [
          {
            required: true,
            message: "请输入角色说明",
            trigger: "blur",
          },
        ],
      },
      // 添加角色的对话框是否可视
      dialogRoleVisible: false,
      // 修改角色表单
      editRole: {
        id: "",
        roleName: "",
        roleDesc: "",
      },
      // 修改角色的对话框是否可视
      editDialogVisible: false,
      // 权限树上的数据
      rightsTree: [],
      defaultProps: {
        label: "authName",
        children: "children",
      },
      // 权限树对话框是否可视
      rightsTreeDialogVisible: false,
      // 保存被选择的权限
      choosedId: [],
      // 保存当前的roleId
      roleId:''
    };
  },
  methods: {
    async getRoleList() {
      let { data: res } = await this.$axios.get("roles");
      if (res.meta.status != 200)
        return this.$messsage.error("获取角色列表失败");
      this.roleList = res.data;
    },
    // 关闭标签
    async closeTag(role, rightId) {
      // 提示框询问是否删除
      let res = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (res == "confirm") {
        // 点击确定后发送用户信息到后台
        let { data: response } = await this.$axios.delete(
          `roles/${role.id}/rights/${rightId}`
        );
        if (response.meta.status != 200)
          return this.$message.error("删除权限失败");
        this.$message.success("删除权限成功");
        // 刷新列表数据
        role.children = response.data;
      } else {
        this.$message("已取消删除权限");
      }
    },
    // 添加角色
    addRole() {
      this.dialogRoleVisible = true;
    },
    // 对话框关闭的回调事件
    closeRoleDialog() {
      // 清除表单数据
      this.$refs.roleForm.resetFields();
    },
    // 点击确定添加角色按钮
    addSubmit() {
      // 先进行一次预校验
      this.$refs.roleForm.validate(async (valid) => {
        if (!valid) return;
        let { data: res } = await this.$axios.post("roles", this.role);
        if (res.meta.status != 201) return this.$message.error("添加角色失败");
        this.getRoleList();
        this.$message.success("添加角色成功");
        this.dialogRoleVisible = false;
      });
    },
    // 编辑角色
    async edit(id) {
      let { data: res } = await this.$axios.get(`roles/${id}`);
      if (res.meta.status != 200) return this.$message.error("获取数据失败");
      this.editRole = res.data;
      this.editDialogVisible = true;
    },
    // 提交编辑对话框
    editSubmit() {
      this.$refs.editRuleForm.validate(async (valid) => {
        if (!valid) return;
        let { data: res } = await this.$axios.put(
          `roles/${this.editRole.roleId}`,
          this.editRole
        );
        if (res.meta.status != 200) return this.$message.error("提交失败");
        this.$message.success("提交成功");
        this.editDialogVisible = false;
        this.getRoleList();
      });
    },
    // 编辑对话框的关闭回调事件
    closeEditDialog() {
      // 清除表单数据
      this.$refs.editRuleForm.resetFields();
    },
    // 删除角色
    async del(id) {
      // 提示框询问是否删除
      let res = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (res == "confirm") {
        // 点击确定后发送用户信息到后台
        let { data: response } = await this.$axios.delete("roles/" + id);
        if (response.meta.status != 200)
          return this.$message.error("删除角色失败");
        this.$message.success("删除角色成功");
        // 刷新列表数据
        this.getRoleList();
      } else {
        this.$message("已取消删除角色");
      }
    },
    async setRight(role) {
      let { data: res } = await this.$axios.get("rights/tree");
      if (res.meta.status != 200) return this.$message.error("获取数据失败");
      this.rightsTree = res.data;
      // 还要获取该id下选取的权限id
      this.choosedId=[]
      this.roleId=role.id
      this.getchoosedId(role,this.choosedId);
      this.rightsTreeDialogVisible = true;
    },
    // 封装一个获取三级权限id的函数
    getchoosedId(node, arr) {
      if (node.children) {
        node.children.forEach((el) => {
          this.getchoosedId(el,arr);
        });
      } else {
        arr.push(node.id);
      }
    },
    // 关闭分配权限对话框提交勾选的权限
    async rightsSubmit(){
      // 获取选中的权限
      let selectedId=[
        ...this.$refs.rightsTree.getCheckedKeys(),
        ...this.$refs.rightsTree.getHalfCheckedKeys()
      ]
      selectedId=selectedId.join()
      let {data:res}=await this.$axios.post(`roles/${this.roleId}/rights`,{rids:selectedId})
      if(res.meta.status!=200)return this.$message.error("更新失败")
      this.$message.success("更新成功")
      this.rightsTreeDialogVisible=false
    },
  },
};
</script>
<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.el-col-5 {
  display: flex;
  align-items: center;
}
.el-tag {
  margin: 10px;
}
.bd-top {
  border-top: 1px solid #eee;
}
.bd-bottom {
  border-bottom: 1px solid #eee;
}
.expand {
  box-sizing: border-box !important;
  padding: 20px !important;
}
.center {
  display: flex;
  align-items: center;
}
</style>